package com.supcon.exchangedata.utils;

import java.io.IOException;
import java.net.*;
import java.util.Enumeration;

/**
 * @author ：icerain.gan
 * @date ：Created in 2020/11/27 14:42
 * @description：网络连接
 * @modified By：
 * @version: $
 */
public class IpUtils {

    public static boolean isAddressAvailable(String ip) throws Exception {
        try {
            InetAddress address = InetAddress.getByName(ip);
            //ping this IP
            if (address instanceof java.net.Inet4Address) {
                System.out.println(ip + " is ipv4 address");
            } else if (address instanceof java.net.Inet6Address) {
                System.out.println(ip + " is ipv6 address");
            } else {
                return false;
            }
            if (address.isReachable(5000)) {
                System.out.println("SUCCESS - ping " + ip);
                return true;
            } else {
                System.out.println(" FAILURE - ping " + ip);
                return false;
            }
        } catch (UnknownHostException e) {
            throw new Exception("未知的ip");
        } catch (IOException e) {
            throw new Exception(e.getMessage());
        }
    }

    public static void printReachableIP(InetAddress remoteAddr, int port) throws SocketException {
        String retIP = null;
        Enumeration<NetworkInterface> netInterfaces;
        try {
            netInterfaces = NetworkInterface.getNetworkInterfaces();
            while (netInterfaces.hasMoreElements()) {
                NetworkInterface ni = netInterfaces.nextElement();
                Enumeration<InetAddress> localAddrs = ni.getInetAddresses();
                while (localAddrs.hasMoreElements()) {
                    InetAddress localAddr = localAddrs.nextElement();
                    if (isReachable(localAddr, remoteAddr, port, 5000)) {
                        retIP = localAddr.getHostAddress();
                        break;
                    }
                }
            }
        } catch (SocketException e) {
            System.out.println("Error occurred while listing all the local networkaddresses.");
        }
        if (retIP == null) {
            System.out.println("NULL reachable local IP is found!");
        } else {
            System.out.println("Reachable local IP is found, it is " + retIP);
        }
    }

    public static boolean isReachable(InetAddress localInetAddr, InetAddress remoteInetAddr, int port, int timeout) {
        boolean isReachable = false;
        Socket socket = null;
        try {
            socket = new Socket();
            // 端口号设置为 0 表示在本地挑选一个可用端口进行连接 SocketAddress localSocketAddr = new
            SocketAddress localSocketAddr = new InetSocketAddress(localInetAddr, 0);
            socket.bind(localSocketAddr);
            InetSocketAddress endpointSocketAddr = new InetSocketAddress(remoteInetAddr, port);
            socket.connect(endpointSocketAddr, timeout);
            System.out.println("SUCCESS -connection established! Local: " + localInetAddr.getHostAddress() + " remote: " + remoteInetAddr.getHostAddress() + " port" + port);
            isReachable = true;
        } catch (IOException e) {
            System.out.println("FAILRE - CAN not connect! Local: " + localInetAddr.getHostAddress() + " remote: " + remoteInetAddr.getHostAddress() + " port" + port);
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    System.out.println("Error occurred while closing socket..");
                }
            }
        }
        return isReachable;
    }

    public static void main(String[] args) {
        try {
            isAddressAvailable("10.10.99.42");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
